<!-- learning-engine-final.html - 动态学习页面 -->
<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title th:text="'智能学习引擎 - ' + ${point.title}">智能学习引擎</title>
  <style>
    /* 保持原有的所有CSS样式不变 */
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    }

    :root {
      --primary-color: #667eea;
      --secondary-color: #764ba2;
      --success-color: #4CAF50;
      --info-color: #2196F3;
      --warning-color: #FF9800;
      --danger-color: #f44336;
    }

    body {
      background: linear-gradient(135deg, var(--primary-color) 0%, var(--secondary-color) 100%);
      color: #333;
      min-height: 100vh;
      padding: 0;
    }

    .app-container {
      max-width: 100%;
      margin: 0 auto;
      min-height: 100vh;
      display: flex;
      flex-direction: column;
    }

    /* 导航栏 */
    .navbar {
      display: flex;
      justify-content: space-between;
      align-items: center;
      background: rgba(255, 255, 255, 0.98);
      padding: 12px 20px;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
      position: sticky;
      top: 0;
      z-index: 100;
    }

    .nav-brand {
      font-size: 20px;
      font-weight: bold;
      color: var(--secondary-color);
      display: flex;
      align-items: center;
    }

    .nav-buttons {
      display: flex;
      gap: 10px;
    }

    .btn {
      padding: 8px 16px;
      border-radius: 6px;
      text-decoration: none;
      font-weight: 600;
      font-size: 14px;
      transition: all 0.3s;
      display: inline-flex;
      align-items: center;
    }

    .btn-outline {
      border: 2px solid var(--secondary-color);
      color: var(--secondary-color);
      background: transparent;
    }

    .btn-outline:hover {
      background: var(--secondary-color);
      color: white;
    }

    /* 主内容区域 */
    .main-content {
      flex: 1;
      padding: 20px;
      max-width: 1200px;
      margin: 0 auto;
      width: 100%;
    }

    /* 学习卡片 */
    .learning-card {
      background: white;
      border-radius: 12px;
      box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
      overflow: hidden;
      margin-bottom: 20px;
    }

    .card-header {
      padding: 20px;
      background: linear-gradient(135deg, #f8f9fa, #e9ecef);
      border-bottom: 1px solid #dee2e6;
    }

    .card-title {
      font-size: 24px;
      color: #333;
      margin-bottom: 8px;
    }

    .card-subtitle {
      color: #666;
      font-size: 14px;
      line-height: 1.5;
    }

    .card-body {
      padding: 25px;
    }

    /* 进度条 */
    .duolingo-progress {
      margin: 20px 0;
      padding: 15px;
      background: #f8f9fa;
      border-radius: 10px;
    }

    .progress-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10px;
    }

    .progress-label {
      font-weight: 600;
      color: #333;
    }

    .progress-percentage {
      color: var(--info-color);
      font-weight: bold;
    }

    .progress-bar-container {
      height: 12px;
      background: #e9ecef;
      border-radius: 6px;
      overflow: hidden;
    }

    .progress-bar {
      height: 100%;
      background: linear-gradient(90deg, var(--info-color), var(--primary-color));
      border-radius: 6px;
      transition: width 0.5s ease;
      width: 0%;
    }

    /* 智能路径指示器 */
    .path-indicator {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 25px;
      padding: 15px;
      background: #f8f9fa;
      border-radius: 10px;
      border-left: 4px solid var(--info-color);
    }

    .path-info h3 {
      color: #333;
      margin-bottom: 5px;
      font-size: 18px;
    }

    .path-info p {
      color: #666;
      font-size: 14px;
      margin: 0;
    }

    .path-tag {
      background: var(--info-color);
      color: white;
      padding: 6px 12px;
      border-radius: 20px;
      font-size: 12px;
      font-weight: bold;
    }

    /* 阶段容器 */
    .stages-container {
      display: grid;
      gap: 20px;
      margin-bottom: 25px;
    }

    .stage-card {
      background: white;
      border: 2px solid #e9ecef;
      border-radius: 10px;
      padding: 20px;
      transition: all 0.3s;
      cursor: pointer;
      position: relative;
    }

    .stage-card.current {
      border-color: var(--info-color);
      background: #f0f8ff;
      transform: translateY(-2px);
      box-shadow: 0 4px 15px rgba(33, 150, 243, 0.15);
    }

    .stage-card.completed {
      border-color: var(--success-color);
      background: #f8fff8;
    }

    .stage-card.locked {
      opacity: 0.6;
      cursor: not-allowed;
    }

    .stage-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 15px;
    }

    .stage-icon {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 15px;
      font-size: 18px;
      flex-shrink: 0;
    }

    .stage-card.current .stage-icon {
      background: var(--info-color);
      color: white;
    }

    .stage-card.completed .stage-icon {
      background: var(--success-color);
      color: white;
    }

    .stage-card.locked .stage-icon {
      background: #6c757d;
      color: white;
    }

    .stage-info {
      flex: 1;
    }

    .stage-name {
      font-weight: 600;
      color: #333;
      margin-bottom: 4px;
    }

    .stage-desc {
      font-size: 13px;
      color: #666;
      line-height: 1.4;
    }

    .stage-status {
      text-align: right;
      font-size: 12px;
      color: #666;
    }

    .stage-duration {
      display: block;
      margin-bottom: 4px;
    }

    /* 学习内容区域 */
    .learning-content {
      min-height: 300px;
      background: white;
      border-radius: 10px;
      padding: 25px;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
    }

    /* 概念理解样式 */
    .concept-content {
      line-height: 1.7;
    }

    .concept-analogy {
      background: #fff3cd;
      border-left: 4px solid #ffc107;
      padding: 15px;
      margin: 20px 0;
      border-radius: 0 8px 8px 0;
    }

    .concept-visual {
      background: #e7f3ff;
      padding: 20px;
      border-radius: 8px;
      margin: 20px 0;
      text-align: center;
    }

    .visual-diagram {
      font-family: 'Courier New', monospace;
      background: white;
      padding: 15px;
      border-radius: 6px;
      margin: 15px 0;
      border: 1px solid #dee2e6;
    }

    /* 测验题目样式 */
    .quiz-container {
      margin: 20px 0;
    }

    .quiz-question {
      margin-bottom: 20px;
      padding: 15px;
      background: #f8f9fa;
      border-radius: 8px;
    }

    .question-text {
      font-weight: 600;
      margin-bottom: 15px;
    }

    .options-container {
      display: flex;
      flex-direction: column;
      gap: 10px;
    }

    .option {
      padding: 12px 15px;
      border: 2px solid #e9ecef;
      border-radius: 8px;
      cursor: pointer;
      transition: all 0.2s;
    }

    .option:hover {
      border-color: var(--info-color);
      background: #f0f8ff;
    }

    .option.selected {
      border-color: var(--info-color);
      background: #e7f3ff;
    }

    .code-exercise {
      margin: 20px 0;
    }

    .code-prompt {
      background: #f8f9fa;
      padding: 15px;
      border-radius: 8px;
      margin-bottom: 20px;
      border-left: 4px solid var(--info-color);
    }

    /* 桌面端代码编辑器 */
    .desktop-code-editor {
      display: none;
    }

    /* 移动端代码构建器 */
    .mobile-code-builder {
      display: none;
    }

    .code-blocks {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
      margin: 15px 0;
    }

    .code-block {
      background: white;
      border: 2px solid #e9ecef;
      padding: 12px 15px;
      border-radius: 8px;
      cursor: grab;
      font-family: 'Courier New', monospace;
      font-size: 14px;
      transition: all 0.2s;
      user-select: none;
    }

    .code-block:hover {
      border-color: var(--info-color);
      transform: translateY(-2px);
    }

    .code-workspace {
      background: #2d2d2d;
      color: #f8f8f2;
      padding: 20px;
      border-radius: 8px;
      min-height: 200px;
      font-family: 'Courier New', monospace;
      margin: 15px 0;
      position: relative;
    }

    .code-line {
      margin-bottom: 8px;
      display: flex;
      align-items: center;
    }

    .line-number {
      color: #6a9955;
      margin-right: 15px;
      min-width: 20px;
    }

    .code-slot {
      display: inline-block;
      min-width: 100px;
      height: 24px;
      border-bottom: 2px dashed #4CAF50;
      margin: 0 5px;
      vertical-align: middle;
    }

    .code-slot.filled {
      border-bottom: none;
      background: #4CAF50;
      color: white;
      padding: 2px 8px;
      border-radius: 4px;
    }

    /* 控制按钮 */
    .action-buttons {
      display: flex;
      justify-content: space-between;
      margin-top: 30px;
      padding-top: 20px;
      border-top: 1px solid #e9ecef;
    }

    .action-btn {
      padding: 12px 25px;
      border: none;
      border-radius: 8px;
      cursor: pointer;
      font-weight: 600;
      transition: all 0.3s;
      display: flex;
      align-items: center;
      gap: 8px;
    }

    .btn-prev {
      background: #6c757d;
      color: white;
    }

    .btn-next {
      background: var(--success-color);
      color: white;
    }

    .btn-prev:disabled {
      background: #ccc;
      cursor: not-allowed;
    }

    /* 移动端优化 */
    @media (max-width: 768px) {
      .main-content {
        padding: 15px;
      }

      .navbar {
        padding: 10px 15px;
      }

      .nav-buttons {
        flex-direction: column;
        gap: 8px;
      }

      .btn {
        padding: 6px 12px;
        font-size: 12px;
      }

      .card-body {
        padding: 20px 15px;
      }

      .path-indicator {
        flex-direction: column;
        align-items: flex-start;
        gap: 10px;
      }

      .path-tag {
        align-self: flex-start;
      }

      .stage-header {
        flex-direction: column;
        align-items: flex-start;
      }

      .stage-icon {
        margin-right: 0;
        margin-bottom: 10px;
      }

      .stage-status {
        align-self: flex-start;
        margin-top: 10px;
      }

      .action-buttons {
        flex-direction: column;
        gap: 10px;
      }

      .action-btn {
        width: 100%;
        justify-content: center;
      }

      /* 移动端显示代码构建器 */
      .mobile-code-builder {
        display: block;
      }
    }

    /* 桌面端优化 */
    @media (min-width: 769px) {
      .desktop-code-editor {
        display: block;
      }

      .stages-container {
        grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
      }

      .main-content {
        padding: 30px;
      }
    }

    /* 大屏幕优化 */
    @media (min-width: 1200px) {
      .main-content {
        padding: 40px;
      }
    }
    .loading-text {
      text-align: center;
      padding: 40px 20px;
      color: var(--text-light);
      font-size: 14px;
    }

    .loading-text i {
      margin-right: 8px;
    }

    .error-text {
      text-align: center;
      padding: 40px 20px;
      color: var(--danger-color);
    }

    .no-points {
      text-align: center;
      padding: 40px 20px;
      color: var(--text-light);
    }
  </style>
</head>
<body>
<div class="app-container">
  <!-- 导航栏 -->
  <nav class="navbar">
    <div class="nav-brand">
      <span style="margin-right: 8px;">🚀</span> 渐进学习平台
    </div>
    <div class="nav-buttons">
      <a th:href="@{/knowledge/gym}" class="btn btn-outline">返回训练馆</a>
      <a th:href="@{/}" class="btn btn-outline">返回首页</a>
    </div>
  </nav>
  <!-- 在导航栏下面添加调试信息 -->
  <div style="background: #f8f9fa; padding: 10px; margin: 10px; border-radius: 5px; border-left: 4px solid #ff9800;">
    <h4>🔍 调试信息</h4>
    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px; font-size: 12px;">
      <div>
        <strong>知识点ID:</strong> <span th:text="${pointId}">-</span>
      </div>
      <div>
        <strong>知识点类型:</strong> <span id="debugKnowledgeType" th:text="${point.knowledgeType}">-</span>
      </div>
      <div>
        <strong>知识点标题:</strong> <span th:text="${point.title}">-</span>
      </div>
      <div>
        <strong>所属包ID:</strong> <span th:text="${point.packageId}">-</span>
      </div>
      <div style="grid-column: 1 / -1;">
        <strong>描述:</strong> <span th:text="${point.description}">-</span>
      </div>
    </div>
  </div>

  <!-- 主内容区域 -->
  <div class="main-content">
    <!-- 学习卡片 -->
    <div class="learning-card">
      <div class="card-header">
        <h1 class="card-title" id="contentTitle" th:text="${point.title}">知识点标题</h1>
        <p class="card-subtitle" id="contentDescription" th:text="${point.description}">知识点描述</p>

        <!-- 多邻国风格进度条 -->
        <div class="duolingo-progress">
          <div class="progress-header">
            <span class="progress-label">学习进度</span>
            <span class="progress-percentage" id="progressPercentage">0%</span>
          </div>
          <div class="progress-bar-container">
            <div class="progress-bar" id="progressBar"></div>
          </div>
        </div>
      </div>

      <div class="card-body">
        <!-- 智能路径指示器 -->
        <div class="path-indicator">
          <div class="path-info">
            <h3>🎯 智能学习路径</h3>
            <p>系统已为你推荐最适合这个知识点的学习阶段</p>
          </div>
          <div class="path-tag" id="pathTypeTag" th:text="${point.knowledgeType}">概念理解型</div>
        </div>

        <!-- 阶段容器 -->
        <div class="stages-container" id="stagesContainer">
          <!-- 阶段会通过JavaScript动态生成 -->
        </div>

        <!-- 学习内容区域 -->
        <div class="learning-content" id="learningContent">
          <div class="loading-state">
            <div style="text-align: center; padding: 40px; color: #666;">
              <div style="font-size: 48px; margin-bottom: 20px;">📚</div>
              <p>选择学习阶段开始</p>
            </div>
          </div>
        </div>

        <!-- 控制按钮 -->
        <div class="action-buttons">
          <button class="action-btn btn-prev" onclick="previousStage()" disabled id="prevBtn">
            ← 上一阶段
          </button>
          <button class="action-btn btn-next" onclick="nextStage()" id="nextBtn">
            下一阶段 →
          </button>
        </div>
      </div>
    </div>
  </div>
</div>

<script>
  // 知识点类型和学习路径配置
  const knowledgeConfigs = {
    // 概念理解型知识点（如IoC、设计模式等）
    "概念理解型": {
      name: "概念理解型",
      stages: [
        {
          id: 1,
          type: "concept",
          name: "核心概念解析",
          icon: "💡",
          description: "通过类比和生活化语言理解抽象概念",
          duration: "8-12分钟",
          required: true
        },
        {
          id: 2,
          type: "analogy",
          name: "生活化类比",
          icon: "🔍",
          description: "用熟悉的场景理解复杂概念",
          duration: "6-10分钟",
          required: true
        },
        {
          id: 3,
          type: "quiz",
          name: "理解检验",
          icon: "🎯",
          description: "快速问答检验概念掌握程度",
          duration: "5-8分钟",
          required: true
        }
      ]
    },

    // API学习型知识点（如集合类、工具类等）
    "API学习型": {
      name: "API学习型",
      stages: [
        {
          id: 1,
          type: "overview",
          name: "API概览",
          icon: "📋",
          description: "了解API的功能和用途",
          duration: "5-8分钟",
          required: true
        },
        {
          id: 2,
          type: "usage",
          name: "使用示例",
          icon: "🔧",
          description: "查看实际使用场景和示例",
          duration: "10-15分钟",
          required: true
        },
        {
          id: 3,
          type: "practice",
          name: "动手练习",
          icon: "💻",
          description: "在代码中实际应用API",
          duration: "12-18分钟",
          required: false
        },
        {
          id: 4,
          type: "quiz",
          name: "应用测验",
          icon: "🎯",
          description: "检验API掌握程度",
          duration: "6-10分钟",
          required: true
        }
      ]
    },

    // 代码实践型知识点（如算法、业务逻辑等）
    "代码实践型": {
      name: "代码实践型",
      stages: [
        {
          id: 1,
          type: "concept",
          name: "思路理解",
          icon: "🧠",
          description: "理解算法思路和实现逻辑",
          duration: "8-12分钟",
          required: true
        },
        {
          id: 2,
          type: "visualization",
          name: "过程可视化",
          icon: "📊",
          description: "通过动画理解执行过程",
          duration: "10-15分钟",
          required: true
        },
        {
          id: 3,
          type: "coding",
          name: "代码实现",
          icon: "💻",
          description: "动手编写和调试代码",
          duration: "15-25分钟",
          required: true
        },
        {
          id: 4,
          type: "optimization",
          name: "优化练习",
          icon: "⚡",
          description: "改进和优化代码实现",
          duration: "10-15分钟",
          required: false
        }
      ]
    }
  };

  // 当前学习状态
  let currentState = {
    knowledgeType: null,
    currentStage: 0,
    completedStages: [],
    currentContent: {
      title: null,
      description: null,
      type: null
    },
    pointId: null
  };

  // 全局变量存储从后端获取的学习内容
  let learningContentData = {};

  // 设备检测
  const isMobile = window.innerWidth <= 768;

  // 初始化页面
  document.addEventListener('DOMContentLoaded', function() {
    // 从调试信息区域获取知识点类型
    const debugElement = document.getElementById('debugKnowledgeType');
    const pathTypeTag = document.getElementById('pathTypeTag');

    // 设置知识点类型
    if (debugElement && debugElement.textContent) {
      currentState.knowledgeType = debugElement.textContent.trim();
    } else if (pathTypeTag && pathTypeTag.textContent) {
      currentState.knowledgeType = pathTypeTag.textContent.trim();
    } else {
      currentState.knowledgeType = "概念理解型"; // 默认值
    }

    // 设置其他属性
    const titleElement = document.getElementById('contentTitle');
    const descriptionElement = document.getElementById('contentDescription');

    currentState.currentContent.title = titleElement ? titleElement.textContent : '未知标题';
    currentState.currentContent.description = descriptionElement ? descriptionElement.textContent : '未知描述';
    currentState.currentContent.type = currentState.knowledgeType;
    currentState.pointId = [[${pointId}]];

    console.log('初始化状态:', currentState); // 调试信息

    // 检查知识点类型是否在配置中
    if (!knowledgeConfigs[currentState.knowledgeType]) {
      console.warn('未找到知识点类型配置:', currentState.knowledgeType);
      // 使用默认配置
      currentState.knowledgeType = "概念理解型";
    }

    renderLearningPath();
    updateContentDisplay();
    updateProgressBar();

    // 设置路径类型标签
    if (pathTypeTag) {
      pathTypeTag.textContent = knowledgeConfigs[currentState.knowledgeType].name;
    }
  });

  // 渲染学习路径
  function renderLearningPath() {
    const container = document.getElementById('stagesContainer');
    const pathConfig = knowledgeConfigs[currentState.knowledgeType];

    container.innerHTML = '';

    pathConfig.stages.forEach((stage, index) => {
      const stageElement = createStageElement(stage, index);
      container.appendChild(stageElement);
    });
  }

  // 创建阶段元素
  function createStageElement(stage, index) {
    const stageDiv = document.createElement('div');
    let stageClass = 'stage-card';

    if (index < currentState.currentStage) {
      stageClass += ' completed';
    } else if (index === currentState.currentStage) {
      stageClass += ' current';
    } else if (index > currentState.currentStage) {
      stageClass += ' locked';
    }

    stageDiv.className = stageClass;
    stageDiv.onclick = () => selectStage(index);

    stageDiv.innerHTML = `
      <div class="stage-header">
        <div class="stage-icon">${stage.icon}</div>
        <div class="stage-info">
          <div class="stage-name">${stage.name}</div>
          <div class="stage-desc">${stage.description}</div>
        </div>
        <div class="stage-status">
          <span class="stage-duration">${stage.duration}</span>
          ${stage.required ? '<span style="color:#666;">必修</span>' : '<span style="color:#999;">选修</span>'}
        </div>
      </div>
    `;

    return stageDiv;
  }

  // 选择阶段
  function selectStage(stageIndex) {
    const pathConfig = knowledgeConfigs[currentState.knowledgeType];

    // 只能选择当前阶段或已完成的阶段
    if (stageIndex > currentState.currentStage) {
      return;
    }

    currentState.currentStage = stageIndex;
    renderLearningPath();
    loadStageContent(pathConfig.stages[stageIndex]);
    updateNavigationButtons();
    updateProgressBar();
  }

  // 加载阶段内容
  function loadStageContent(stage) {
    const contentArea = document.getElementById('learningContent');

    // 显示加载状态
    contentArea.innerHTML = `
      <div class="loading-text">
        <div style="font-size: 48px; margin-bottom: 20px;">⏳</div>
        <p>加载学习内容中...</p>
      </div>
    `;

    // 首先加载学习内容，然后根据阶段类型渲染
    loadLearningContent().then(() => {
      switch (stage.type) {
        case 'concept':
          contentArea.innerHTML = renderConceptContent();
          break;
        case 'analogy':
          contentArea.innerHTML = renderAnalogyContent();
          break;
        case 'coding':
          contentArea.innerHTML = isMobile ? renderMobileCodingContent() : renderDesktopCodingContent();
          break;
        case 'quiz':
          contentArea.innerHTML = renderQuizContent();
          break;
        case 'overview':
          contentArea.innerHTML = renderOverviewContent();
          break;
        case 'usage':
          contentArea.innerHTML = renderUsageContent();
          break;
        case 'practice':
          contentArea.innerHTML = renderPracticeContent();
          break;
        case 'visualization':
          contentArea.innerHTML = renderVisualizationContent();
          break;
        case 'optimization':
          contentArea.innerHTML = renderOptimizationContent();
          break;
        default:
          contentArea.innerHTML = renderDefaultContent(stage);
      }
    }).catch(error => {
      console.error('加载学习内容失败:', error);
      contentArea.innerHTML = `
        <div class="error-text">
          <div style="font-size: 48px; margin-bottom: 20px;">❌</div>
          <p>加载内容失败，请刷新页面重试</p>
          <button onclick="retryLoadContent()" style="margin-top: 10px; padding: 8px 16px; background: var(--danger-color); color: white; border: none; border-radius: 4px; cursor: pointer;">
            重试加载
          </button>
        </div>
      `;
    });
  }

  // 从后端加载学习内容
  function loadLearningContent() {
    return fetch('/knowledge/training/' + currentState.pointId + '/learning-content')
            .then(response => {
              if (!response.ok) {
                throw new Error('网络响应不正常');
              }
              return response.json();
            })
            .then(data => {
              learningContentData = data;
              return data;
            });
  }

  // 重试加载内容
  function retryLoadContent() {
    const pathConfig = knowledgeConfigs[currentState.knowledgeType];
    loadStageContent(pathConfig.stages[currentState.currentStage]);
  }

  // 渲染概念理解内容 - 使用动态数据
  function renderConceptContent() {
    const conceptData = learningContentData.conceptContent ||
            generateDynamicConcept(currentState.currentContent.title);

    return `
      <div class="concept-content">
        <h3>💡 ${currentState.currentContent.title} 核心概念</h3>
        <p>${currentState.currentContent.description}</p>

        <div class="concept-analogy">
          <h4>🤔 核心思想</h4>
          <p>${conceptData}</p>
        </div>

        <div class="concept-visual">
          <h4>🔄 工作原理</h4>
          <div class="visual-diagram">
            ${getConceptDiagram(currentState.currentContent.title)}
          </div>
        </div>

        <div style="margin-top: 20px;">
          <h4>🎯 关键要点：</h4>
          <ul style="line-height: 1.8;">
            <li><strong>核心作用：</strong>理解其主要功能和用途</li>
            <li><strong>工作方式：</strong>掌握其基本运作原理</li>
            <li><strong>应用场景：</strong>了解适用的场景和限制</li>
            <li><strong>与其他概念的关系：</strong>理解其在技术体系中的位置</li>
          </ul>
        </div>
      </div>
    `;
  }

  // 渲染生活化类比内容 - 使用动态数据
  function renderAnalogyContent() {
    const analogyData = learningContentData.analogyContent ||
            generateDynamicAnalogy(currentState.currentContent.title);

    return `
      <div class="concept-content">
        <h3>🔍 ${currentState.currentContent.title} 生活化类比</h3>

        <div style="display: grid; gap: 20px; margin-top: 20px;">
          <div style="background: #e7f3ff; padding: 20px; border-radius: 10px;">
            <h4>🎯 理解类比</h4>
            <p>${analogyData}</p>
          </div>

          <div style="background: #f0f8ff; padding: 20px; border-radius: 10px;">
            <h4>💡 学习提示</h4>
            <p>尝试将这个概念与你熟悉的事物联系起来，这样能帮助你更好地理解和记忆。</p>
          </div>
        </div>
      </div>
    `;
  }

  // 根据知识点标题生成概念图示
  function getConceptDiagram(title) {
    if (title.includes('IoC') || title.includes('Spring') || title.includes('依赖注入')) {
      return `应用程序 → Spring容器 → 管理Bean生命周期 → 依赖注入`;
    } else if (title.includes('多线程') || title.includes('线程')) {
      return `主线程 → 创建子线程 → 线程同步 → 资源共享`;
    } else if (title.includes('集合') || title.includes('List') || title.includes('Map')) {
      return `数据输入 → 集合处理 → 数据输出 → 性能优化`;
    } else if (title.includes('异常') || title.includes('Exception')) {
      return `代码执行 → 异常发生 → 异常处理 → 程序恢复`;
    } else {
      return `输入 → 处理过程 → 输出 → 结果验证`;
    }
  }

  // 动态生成概念内容（备用方案）
  function generateDynamicConcept(title) {
    if (title.includes('IoC') || title.includes('依赖注入')) {
      return 'IoC（控制反转）是一种设计原则，用来将对象的创建和绑定从使用它们的代码中解耦。在传统的程序设计中，我们直接在代码中创建对象，而使用IoC后，对象的创建和管理由容器负责，我们只需要定义好依赖关系即可。';
    } else if (title.includes('多线程')) {
      return '多线程允许程序同时执行多个任务，提高CPU利用率和程序响应性。通过创建多个线程，可以让程序在执行耗时操作时仍能响应用户交互，或者利用多核CPU的优势并行处理任务。';
    } else if (title.includes('集合')) {
      return '集合框架提供了一系列用于存储和操作数据组的数据结构。不同的集合类有不同的特性和适用场景，如List适合有序存储，Set适合去重存储，Map适合键值对存储。';
    }
    return `让我们深入理解 ${title} 的核心概念和基本原理。这个概念在软件开发中扮演着重要角色，掌握它对于提升编程能力至关重要。`;
  }

  // 动态生成类比内容（备用方案）
  function generateDynamicAnalogy(title) {
    if (title.includes('IoC') || title.includes('依赖注入')) {
      return 'IoC就像餐厅的点餐系统：传统方式是你自己去厨房点菜（直接创建对象），而IoC是你告诉服务员（容器），服务员帮你协调一切。你不需要关心菜是怎么做的，只需要享受美食（使用对象）。';
    } else if (title.includes('多线程')) {
      return '多线程就像厨房里的多位厨师：单线程就像只有一位厨师，他必须一道菜一道菜地做；而多线程就像有多位厨师，他们可以同时准备不同的菜品，大大提高效率。';
    } else if (title.includes('集合')) {
      return '集合就像不同的储物容器：List就像书架，书按顺序摆放；Set就像储物箱，每个物品只放一次；Map就像带标签的储物柜，通过标签快速找到物品。';
    }
    return `想象一下 ${title} 就像日常生活中的某个场景，通过这种类比可以帮助你更好地理解这个抽象概念的实际应用和意义。`;
  }

  // 渲染API概览内容
  function renderOverviewContent() {
    return `
      <div class="concept-content">
        <h3>📋 ${currentState.currentContent.title} API概览</h3>
        <p>了解${currentState.currentContent.title}的主要功能和用途</p>

        <div class="concept-visual">
          <h4>🔧 主要功能</h4>
          <ul style="text-align: left; line-height: 1.8;">
            <li>核心功能1：描述功能用途</li>
            <li>核心功能2：描述功能用途</li>
            <li>核心功能3：描述功能用途</li>
          </ul>
        </div>
      </div>
    `;
  }

  // 渲染使用示例内容
  function renderUsageContent() {
    return `
      <div class="code-exercise">
        <h3>🔧 ${currentState.currentContent.title} 使用示例</h3>
        <div class="code-prompt">
          <p><strong>示例：</strong>${currentState.currentContent.title}的基本使用方法</p>
        </div>

        <div class="desktop-code-editor">
          <pre style="background: #2d2d2d; color: #f8f8f2; padding: 20px; border-radius: 8px; font-family: 'Courier New', monospace;">
// ${currentState.currentContent.title} 使用示例
public class Example {
    public static void main(String[] args) {
        // 在这里展示使用示例
        System.out.println("示例代码");
    }
}</pre>
        </div>
      </div>
    `;
  }

  // 渲染桌面端代码练习
  function renderDesktopCodingContent() {
    return `
      <div class="code-exercise">
        <h3>💻 代码实践：${currentState.currentContent.title}</h3>

        <div class="code-prompt">
          <p><strong>任务：</strong>完成以下代码实现，理解${currentState.currentContent.title}的核心概念</p>
        </div>

        <div class="desktop-code-editor">
          <div style="background: #2d2d2d; color: #f8f8f2; padding: 20px; border-radius: 8px; font-family: 'Courier New', monospace;">
            <div class="code-line"><span style="color: #569cd6;">public class</span> <span style="color: #4ec9b0;">Practice</span> {</div>
            <div class="code-line">&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: #569cd6;">public static void</span> <span style="color: #dcdcaa;">main</span>(String[] args) {</div>
            <div class="code-line">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<textarea placeholder="// 在这里实现代码逻辑" style="width: 100%; background: #1e1e1e; color: #f8f8f2; border: 1px solid #444; padding: 8px; border-radius: 4px; min-height: 80px; font-family: 'Courier New', monospace;"></textarea></div>
            <div class="code-line">&nbsp;&nbsp;&nbsp;&nbsp;}</div>
            <div class="code-line">}</div>
          </div>
        </div>

        <div style="margin-top: 20px;">
          <button class="action-btn btn-next" onclick="runCode()" style="background: var(--info-color);">
            🔧 运行测试
          </button>
        </div>
      </div>
    `;
  }

  // 渲染移动端代码构建器
  function renderMobileCodingContent() {
    return `
      <div class="code-exercise">
        <h3>📱 代码构建：${currentState.currentContent.title}</h3>

        <div class="code-prompt">
          <p><strong>任务：</strong>通过拖拽代码块理解${currentState.currentContent.title}的实现</p>
        </div>

        <div class="mobile-code-builder">
          <h4>可用代码块：</h4>
          <div class="code-blocks">
            <div class="code-block" draggable="true" data-code="// 代码块1">代码块1</div>
            <div class="code-block" draggable="true" data-code="// 代码块2">代码块2</div>
            <div class="code-block" draggable="true" data-code="// 代码块3">代码块3</div>
            <div class="code-block" draggable="true" data-code="// 代码块4">代码块4</div>
          </div>

          <h4 style="margin-top: 20px;">代码工作区：</h4>
          <div class="code-workspace">
            <div class="code-line">
              <span class="line-number">1</span>
              <span>public class Practice {</span>
            </div>
            <div class="code-line">
              <span class="line-number">2</span>
              <span>&nbsp;&nbsp;&nbsp;&nbsp;public static void main(String[] args) {</span>
            </div>
            <div class="code-line">
              <span class="line-number">3</span>
              <span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
              <div class="code-slot" id="slot1" ondrop="dropCode(event)" ondragover="allowDrop(event)"></div>
            </div>
            <div class="code-line">
              <span class="line-number">4</span>
              <span>&nbsp;&nbsp;&nbsp;&nbsp;}</span>
            </div>
            <div class="code-line">
              <span class="line-number">5</span>
              <span>}</span>
            </div>
          </div>
        </div>

        <div style="margin-top: 20px;">
          <button class="action-btn btn-next" onclick="checkMobileCode()" style="background: var(--info-color);">
            ✅ 检查答案
          </button>
        </div>
      </div>
    `;
  }

  // ========== 渲染测验内容，从后端获取题目 ==========
  function renderQuizContent() {
    let quizContent = `
      <div class="quiz-container">
        <h3>🎯 知识检验</h3>
        <p>完成以下题目来检验你的理解程度</p>
        <div id="quizQuestionsContainer">
          <div class="loading-text">
            <div style="font-size: 48px; margin-bottom: 20px;">⏳</div>
            <p>加载题目中...</p>
          </div>
        </div>
      </div>
    `;

    // 从后端获取测验题目
    fetch('/knowledge/training/' + currentState.pointId + '/quiz-questions')
            .then(response => {
              if (!response.ok) {
                throw new Error('网络响应不正常');
              }
              return response.json();
            })
            .then(questions => {
              if (questions && questions.length > 0) {
                renderQuizQuestions(questions);
              } else {
                document.getElementById('quizQuestionsContainer').innerHTML =
                        '<div class="no-points" style="text-align: center; padding: 40px 20px; color: var(--text-light);">' +
                        '<div style="font-size: 48px; margin-bottom: 20px;">📝</div>' +
                        '<p>暂无测验题目</p>' +
                        '</div>';
              }
            })
            .catch(error => {
              console.error('加载题目失败:', error);
              document.getElementById('quizQuestionsContainer').innerHTML =
                      '<div class="error-text" style="text-align: center; padding: 40px 20px; color: var(--danger-color);">' +
                      '<div style="font-size: 48px; margin-bottom: 20px;">❌</div>' +
                      '<p>加载题目失败，请重试</p>' +
                      '<button class="retry-btn" onclick="retryLoadQuiz()" ' +
                      'style="margin-top: 10px; padding: 5px 15px; background: var(--danger-color); color: white; border: none; border-radius: 4px; cursor: pointer;">' +
                      '重试</button>' +
                      '</div>';
            });

    return quizContent;
  }

  // 重试加载测验题目
  function retryLoadQuiz() {
    const pathConfig = knowledgeConfigs[currentState.knowledgeType];
    loadStageContent(pathConfig.stages[currentState.currentStage]);
  }

  // 渲染测验题目
  function renderQuizQuestions(questions) {
    let questionsHTML = '';

    questions.forEach((question, index) => {
      // 使用content字段作为问题内容
      const questionText = question.content || '暂无题目内容';

      questionsHTML += `
        <div class="quiz-question">
          <div class="question-text">${index + 1}. ${questionText}</div>
          <div class="options-container">
      `;

      if (question.questionType === 'choice' && question.options) {
        try {
          const options = JSON.parse(question.options);
          options.forEach((option, optIndex) => {
            const optionLabel = String.fromCharCode(65 + optIndex); // A, B, C, D
            questionsHTML += `<div class="option" onclick="selectOption(this)">${optionLabel}. ${option}</div>`;
          });
        } catch (e) {
          console.error('解析选项失败:', e);
          questionsHTML += '<p>选项解析错误</p>';
        }
      } else if (question.questionType === 'code') {
        questionsHTML += `
          <textarea style="width: 100%; min-height: 150px; padding: 10px; border: 1px solid #ddd; border-radius: 5px; margin-top: 10px; font-family: 'Courier New', monospace;"
                    placeholder="请在此编写你的代码..."></textarea>
        `;
      } else if (question.questionType === 'text') {
        questionsHTML += `
          <textarea style="width: 100%; min-height: 100px; padding: 10px; border: 1px solid #ddd; border-radius: 5px; margin-top: 10px;"
                    placeholder="请在此输入你的答案..."></textarea>
        `;
      } else {
        questionsHTML += '<p>暂不支持该题型</p>';
      }

      questionsHTML += `
          </div>
        </div>
      `;
    });

    questionsHTML += `
      <div style="margin-top: 20px; text-align: center;">
        <button class="action-btn btn-next" onclick="submitQuiz()" style="background: var(--info-color);">
          ✅ 提交答案
        </button>
      </div>
    `;

    document.getElementById('quizQuestionsContainer').innerHTML = questionsHTML;
  }

  // 选择选项
  function selectOption(element) {
    // 移除同一问题中其他选项的选中状态
    const parent = element.parentElement;
    const options = parent.querySelectorAll('.option');
    options.forEach(opt => opt.classList.remove('selected'));

    // 设置当前选项为选中状态
    element.classList.add('selected');
  }

  // 提交测验
  function submitQuiz() {
    alert('答案已提交！在实际项目中，这里会验证答案并给出反馈。');
    // 标记当前阶段为已完成
    if (!currentState.completedStages.includes(currentState.currentStage)) {
      currentState.completedStages.push(currentState.currentStage);
    }
    updateProgressBar();
  }

  // 更新内容显示
  function updateContentDisplay() {
    // 内容已通过Thymeleaf设置，这里主要更新动态部分
  }

  // 更新导航按钮
  function updateNavigationButtons() {
    const prevBtn = document.getElementById('prevBtn');
    const nextBtn = document.getElementById('nextBtn');
    const pathConfig = knowledgeConfigs[currentState.knowledgeType];

    prevBtn.disabled = currentState.currentStage === 0;

    if (currentState.currentStage === pathConfig.stages.length - 1) {
      nextBtn.textContent = '完成学习 🎉';
    } else {
      nextBtn.textContent = '下一阶段 →';
    }
  }

  // 更新进度条
  function updateProgressBar() {
    const pathConfig = knowledgeConfigs[currentState.knowledgeType];
    const totalStages = pathConfig.stages.length;
    const completedStages = currentState.completedStages.length;

    const progressPercentage = Math.round((completedStages / totalStages) * 100);

    document.getElementById('progressBar').style.width = `${progressPercentage}%`;
    document.getElementById('progressPercentage').textContent = `${progressPercentage}%`;
  }

  // 上一阶段
  function previousStage() {
    if (currentState.currentStage > 0) {
      currentState.currentStage--;
      renderLearningPath();
      const pathConfig = knowledgeConfigs[currentState.knowledgeType];
      loadStageContent(pathConfig.stages[currentState.currentStage]);
      updateNavigationButtons();
      updateProgressBar();
    }
  }

  // 下一阶段
  function nextStage() {
    const pathConfig = knowledgeConfigs[currentState.knowledgeType];

    if (currentState.currentStage < pathConfig.stages.length - 1) {
      currentState.currentStage++;
      renderLearningPath();
      loadStageContent(pathConfig.stages[currentState.currentStage]);
      updateNavigationButtons();
      updateProgressBar();
    } else {
      completeLearning();
    }
  }

  // ========== 完成学习，提交学习记录 ==========
  function completeLearning() {
    const contentArea = document.getElementById('learningContent');
    contentArea.innerHTML = `
      <div style="text-align: center; padding: 40px;">
        <div style="font-size: 64px; margin-bottom: 20px;">🎉</div>
        <h2 style="color: var(--success-color); margin-bottom: 15px;">恭喜完成学习！</h2>
        <p style="color: #666; margin-bottom: 30px;">你已成功掌握 <strong>${currentState.currentContent.title}</strong> 的核心概念</p>

        <div style="margin: 20px 0;">
          <label style="display: block; margin-bottom: 10px;">学习评价：</label>
          <select id="learningRating" style="padding: 8px; border-radius: 4px; border: 1px solid #ddd;">
            <option value="5">★★★★★ 非常满意</option>
            <option value="4">★★★★ 满意</option>
            <option value="3">★★★ 一般</option>
            <option value="2">★★ 不太满意</option>
            <option value="1">★ 很不满意</option>
          </select>
        </div>

        <div style="margin: 20px 0;">
          <label style="display: block; margin-bottom: 10px;">学习笔记：</label>
          <textarea id="learningNotes" style="width: 100%; min-height: 80px; padding: 10px; border: 1px solid #ddd; border-radius: 5px;"
                    placeholder="记录学习心得..."></textarea>
        </div>

        <div style="display: flex; gap: 15px; justify-content: center;">
          <button class="action-btn" onclick="submitLearningComplete()" style="background: var(--primary-color);">
            ✅ 提交学习记录
          </button>
          <button class="action-btn" onclick="goToNextPoint()" style="background: var(--info-color);">
            📚 下一个知识点
          </button>
        </div>
      </div>
    `;

    document.querySelector('.action-buttons').style.display = 'none';
  }

  // 提交学习完成记录
  function submitLearningComplete() {
    const rating = document.getElementById('learningRating').value;
    const notes = document.getElementById('learningNotes').value;

    const formData = new FormData();
    formData.append('pointId', currentState.pointId);
    formData.append('rating', rating);
    formData.append('notes', notes);

    fetch('/knowledge/training/complete', {
      method: 'POST',
      body: formData
    })
            .then(response => response.text())
            .then(result => {
              if (result === 'success') {
                alert('学习记录提交成功！');
                goToNextPoint();
              } else {
                alert('提交失败：' + result);
              }
            })
            .catch(error => {
              console.error('提交学习记录失败:', error);
              alert('提交失败，请重试');
            });
  }

  // 跳转到练习页面
  function goToPractice() {
    window.location.href = '/practice?pointId=' + currentState.pointId;
  }

  // 跳转到下一个知识点
  function goToNextPoint() {
    window.location.href = '/knowledge/gym';
  }

  // 初始化代码块拖拽
  document.addEventListener('DOMContentLoaded', function() {
    const codeBlocks = document.querySelectorAll('.code-block');
    codeBlocks.forEach(block => {
      block.addEventListener('dragstart', function(event) {
        event.dataTransfer.setData("text", event.target.getAttribute('data-code'));
      });
    });
  });

  // 允许拖拽
  function allowDrop(event) {
    event.preventDefault();
  }

  // 处理拖拽放置
  function dropCode(event) {
    event.preventDefault();
    const code = event.dataTransfer.getData("text");
    event.target.textContent = code;
    event.target.className = "code-slot filled";
  }

  // 以下为占位函数，用于未实现的阶段类型
  function renderDefaultContent(stage) {
    return `
      <div class="concept-content">
        <h3>${stage.icon} ${stage.name}</h3>
        <p>${stage.description}</p>
        <div style="text-align: center; padding: 40px; color: #666;">
          <div style="font-size: 48px; margin-bottom: 20px;">🔧</div>
          <p>此阶段内容正在开发中...</p>
        </div>
      </div>
    `;
  }

  function renderPracticeContent() {
    return renderDefaultContent({icon: "💻", name: "动手练习", description: "在实际代码中应用所学知识"});
  }

  function renderVisualizationContent() {
    return renderDefaultContent({icon: "📊", name: "过程可视化", description: "通过动画理解执行过程"});
  }

  function renderOptimizationContent() {
    return renderDefaultContent({icon: "⚡", name: "优化练习", description: "改进和优化代码实现"});
  }

  function runCode() {
    alert('代码运行功能正在开发中...');
  }

  function checkMobileCode() {
    alert('代码检查功能正在开发中...');
  }
</script>
</body>
</html>